<?php
namespace Mapi\Controller;
use Think\Controller\RestController;
/**
 * 资源服务器
 */
class UploadController extends RestController{
	private $rotate = 0;

	public function uploadVideo(){
		$this->uploadify('Video');
	}

	/**
	 * 上传图片
	 * @param  string $type 上传类型
	 * @return [type]       [description]
	 */
	public function uploadify($type = 'Image') {

		apigetpost();
		if(IS_POST) {
			$file = $_FILES['Filedata']['name'];
			$file = explode('.', $file);

			$this->rotate=$file[3];
			$info = $this->_uploadAttach($type,true);			
			
			
			if(is_array($info['Filedata']) && !empty($info['Filedata'])) {
				$info = $info['Filedata'];
				$dataGet['filename'] = $info['savename'];
				$dataGet['filetype'] = $info['type'];
				$dataGet['oriwidth'] = $info['oriWidth'];
				$dataGet['oriheight'] = $info['oriHeight'];
				$dataGet['thumbwidth'] = $info['thumbWidth'];
				$dataGet['thumbheight'] = $info['thumbHeight'];
				$dataGet['filesize'] = formatBytes($info['size']);
				$dataGet['filepath'] = $info['savepath'];
				$dataGet['thumb'] = $info['thumb'];
				$dataGet['uploadtime'] = time();
				$dataGet['aid'] = $file[1];
				$dataGet['sort'] = $file[2];
				$dataGet['ip'] = I('server.HTTP_X_REAL_IP');
				//$attchmentType=$type;
				$dataGet['type'] = strtolower($type);

				$res = M('Attachment')->add($dataGet);
				if(!$res) {
					$message['resultCode'] = 1;
					$message['message'] = '上传失败，请重试';	
				} else {
					/*if(in_array($info['ext'], array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'))) {
						M('Article')->where(array('id' => $file[1]))->save(array('is_video' => 1));
					}*/

					$this->updateAttachByAid($file[1], $res);
					switch($type){
						case "Image":
							M('Article')->where('id = ' . $file[1] . ' AND indexpic = ""')->save(array('indexpic' => $info['thumb']));
						break;
						case "Video":
							M('Article')->where('id = ' . $file[1] )->save(array('indexpic' => $info['thumb']));
						break;
					}
					$message['resultCode'] = 0;
					$message['message'] = '';
					$message['attachid'] = $res;	
					$message['articleid'] = $file[1];		
				}

			} else {
				$message['resultCode'] = 1;
				$message['message'] = $info;				
			}

			$this->ajaxReturn($message);	
		}

		$this->display('Article:createArticle');
	}

	protected  function get_video_orientation($video_path) {
	   /* $cmd =  "/usr/bin/ffprobe " . $video_path . " -show_streams 2>/dev/null";
	    $result = shell_exec($cmd);*/
	 
	    $orientation = 0;
	    /*if(strpos($result, 'TAG:rotate') !== FALSE) {
	        $result = explode("\n", $result);
	        foreach($result as $line) {
	            if(strpos($line, 'TAG:rotate') !== FALSE) {
	                $stream_info = explode("=", $line);
	                $orientation = $stream_info[1];
	            }
	        }
	    }*/
	    return $orientation;
	}


	/**
	 * 上传附件
	 * @return [type] [description]
	 */
	protected function _uploadAttach($type, $thumb = false) {
		$ext_arr = array(
                'Image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
                'Photo' => array('jpg', 'jpeg', 'png'),
                'Flash' => array('swf', 'flv'),
                'MobileFlash' => array('mp4', 'avi', 'mov'), 
                'Video' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb','mp4', 'mov'),
                'File' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2','pdf')
        );
    
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 0 ;// 设置附件上传大小
        $saveRule=$upload->saveRule = date('ymdHis', time()) . '_' . mt_rand(5);
        $upload->autoSub = true;//使用子目录保存上传文件
        $upload->subType = 'custom';//使用日期模式创建子目录
        $upload->subName = date('Y') . '/' . date('m') . '/' . date('d');
        $upload->dateFormat = 'Ymd';//设置子目录日期格式
        $upload->allowExts  = $ext_arr[$type];// 设置附件上传类型
        $upload->rootPath  =  UPLOAD_PATH;
        $upload->savePath =  $type . '/';// 设置附件上传目录
        $upload->thumb = $thumb; //生成缩略图
        $upload->thumbMaxWidth = C('THUMB_MAX_WIDTH'); //缩略图最大宽度
        $upload->thumbMaxHeight = C('THUMB_MAX_HEIGHT'); //缩略图最大高度
        $upload->thumbRemoveOrigin = true;
    
        // 上传文件
        $info   =   $upload->upload();

        if(!$info) {        	
		   return $upload->getError();
        }else{
        	if($thumb && strtolower($type)=='image'){
        		$image = new \Think\Image(); 
        		
        		$image->open($upload->rootPath.$info['Filedata']['savepath'].$info['Filedata']['savename']);
        		$info['Filedata']['oriWidth']=$image->width(); 
        		$info['Filedata']['oriHeight']=$image->height();
        		$filename=explode(".",$info['Filedata']['savename']);
				$filename=$filename[0];
        		$info['Filedata']['thumb']=$info['Filedata']['savepath'].$filename.'_thumb.jpg';
        		$image->thumb(C('THUMB_MAX_WIDTH'), C('THUMB_MAX_HEIGHT'),1)->save($upload->rootPath.$info['Filedata']['thumb']); 
        		$info['Filedata']['thumbWidth']=$image->width(); 
        		$info['Filedata']['thumbHeight']=$image->height();   		
        	}else if($thumb && strtolower($type)=='video'){
        		extension_loaded ('ffmpeg');
    			$movefile = realpath(UPLOAD_PATH)."/".$info['Filedata']['savepath'].$info['Filedata']['savename']; 
    			$filename=explode(".",$info['Filedata']['savename']);
				$filename=$filename[0];
				$mov = new \ffmpeg_movie($movefile);
				$info['Filedata']['oriWidth']=$mov->getFrameWidth();
        		$info['Filedata']['oriHeight']=$mov->getFrameHeight();

        		$out=realpath(UPLOAD_PATH)."/".$info['Filedata']['savepath'].$filename.'_ori_thumb.jpg';

        		$cmd="ffmpeg -i {$movefile} -f image2 -ss 10 -s {$info['Filedata']['oriWidth']}*{$info['Filedata']['oriHeight']} -vframes 1 {$out}";
        		exec($cmd);

				/*$f = $mov->getFrame(5);
				$gd_image = $f->toGDImage();*/
				$info['Filedata']['thumb']=$info['Filedata']['savepath'].$filename.'_thumb.jpg';

				


				if ($this->rotate!=0) {
				    $gd_image = imagecreatefromjpeg($out);
				    $gd_image = imagerotate($gd_image, 360-$this->rotate, 0);
				    imagepng($gd_image, $out);
					imagedestroy($gd_image);
				}

				$image = new \Think\Image(); 
				$image->open($out);				
				$image->thumb(C('THUMB_MAX_WIDTH'), C('THUMB_MAX_HEIGHT'),1)->save(UPLOAD_PATH.$info['Filedata']['thumb']); 
				$info['Filedata']['thumbWidth']=$image->width(); 
        		$info['Filedata']['thumbHeight']=$image->height();
        	}
		   return $info;
        }

	}



	/**
	 * 更新附近的排列位置
	 * @return [type] [description]
	 */
	/*public function updateAttachSort() {
		apigetpost();
		$attId = intval(I('post.attId'));
		$sortId = I('post.sortId', 0);
		$userToken = I('post.userToken');
		$uid = F($userToken);

		if(!$uid) {
			$message['resultCode'] = 1;
			$message['message'] = '用户未登录';
			$this->ajaxReturn($message);
		}

		if(!$attId) {
			$message['resultCode'] = 1;
			$message['message'] = '附件ID未知';
			$this->ajaxReturn($message);
		}

		$res = M('Attachment')->where(array('attachid' => $attId))->save(array('sort' => $sortId));

		if($res !== false) {
			$message['resultCode'] = 0;
			$message['message'] = '更新成功';
			$this->ajaxReturn($message);			
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '更新失败';
			$this->ajaxReturn($message);
		}	
	}*/

	/**
	 * 删除已上传的附件列表
	 * @return [type] [description]
	 */
	/*public function delUploadedAttach() {
		apigetpost();
		$attIds = I('post.attIds');
		$userToken = I('post.userToken');
		$uid = F($userToken);

		// if(!$uid) {
		// 	$message['resultCode'] = 1;
		// 	$message['message'] = '用户未登录';
		// 	$this->ajaxReturn($message);
		// }

		if(!$attIds) {
			$message['resultCode'] = 1;
			$message['message'] = '删除ID不能为空';
			$this->ajaxReturn($message);
		}

		$map['attachid'] = array('in', $attIds);
		$attachInfo = M('Attachment')->field('aid, filetype')->where($map)->find();
		$res = M('Attachment')->where($map)->save(array('aid' => 0));
		if($res != false) {
			$flashType = array('video/mp4', 'video/x-msvideo', 'video/quicktime');
			if(in_array($attachInfo['filetype'], $flashType)) {
				M('Article')->where(array('id' => $attachInfo['aid']))->save(array('is_video' => 0));
			}

			$message['resultCode'] = 0;
			$message['message'] = '更新成功';
			$this->ajaxReturn($message);			
		} else {
			$message['resultCode'] = 1;
			$message['message'] = '更新失败';
			$this->ajaxReturn($message);
		}			

	}*/


	public function getImageSize($url){
		if($url){
			 $image = new \Think\Image();
			 if(is_file(UPLOAD_PATH.$url)){
			 	 $imageinfo=$image->open(UPLOAD_PATH.$url);
			 	 $attchment['thumbWidth']=$imageinfo->width();
                 $attchment['thumbHeight']=$imageinfo->height();
                 $message['resultCode']=0;
				 $message['message'] = '';
				 $message['attchment']=$attchment;
			 }else{
			 	$message['resultCode']=1;
			 	$message['message'] = '图片不存在';
			 }
		}
		$this->ajaxReturn($message);
	}

	/**
	 * 推送M2O附件
	 * @param  [type] $token [description]
	 * @param  [type] $file  [description]
	 * @return [type]        [description]
	 */
	public function pushM2oAttchment($token,$file){
			$data['access_token'] = $token;
			$image = new \Think\Image();
			$image->open(UPLOAD_PATH.$file);
			if($image->width()>2000 ||$image->height()>2000){
				$a=explode(".",$file);
				$b=str_replace('.'.$a[count($a)-1],"",$file);
				$image->thumb(2000, 2000)->save(UPLOAD_PATH.$b."_new.".$a[count($a)-1]);				
				rename(UPLOAD_PATH.$file, UPLOAD_PATH.$b."_ogi.".$a[count($a)-1]);
				rename(UPLOAD_PATH.$b."_new.".$a[count($a)-1], UPLOAD_PATH.$file);				
			}
			
			$data['Filedata'] = '@' . UPLOAD_PATH . $file;
			$fileinfo = gethttpcurl('http://mobile.appwuhan.com/helper/uploadAttach.php', array('postarr' => $data));
			$fileinfo = json_decode($fileinfo, true);
			$this->ajaxReturn($fileinfo[0]);
	}

	public function test(){
		phpinfo();
	}

}